using Godot;
using System;

public partial class UiHandChooseblock : Ui
{
	private GridContainer _gridContainer;
	private GridContainer _equipItemGrid;
	private UiInventory _inventory;
	private OptionButton _optionButton;
	private Player _player;
	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		_gridContainer = this.GetNode<GridContainer>("%GridContainer");
		_optionButton = this.GetNode<OptionButton>("%OptionButton");
		var Game = GetNode<Game>("/root/Game");
		var UIControl = GetNode<UIControl>("/root/UIControl");
		_inventory = UIControl.GetGuiViewManager().GetChild(0).GetNode<UiInventory>("%UiInventory");
		_equipItemGrid = _inventory.GetNode<GridContainer>("%EquipGrid");
		_player = Game.get_player();

		if(!(_player.CharacterData as PlayerData).Maps.Contains("随机"))
		{(_player.CharacterData as PlayerData).Maps.Add("随机");}
		
		var children = _gridContainer.GetChildren();
		foreach(var child in children)
		{
			HandChooseSlot slot = (HandChooseSlot)child;
			slot.Initialize();
		}
		_optionButton.ItemSelected += OnOptionButtonItemSelected;
	}


    // Called every frame. 'delta' is the elapsed time since the previous frame.
    public override void _Process(double delta)
	{
		var Game = GetNode<Game>("/root/Game");
		var UIControl = GetNode<UIControl>("/root/UIControl");
		if(this.Visible == true)
		{
			
			if(Input.IsActionJustReleased("tab"))
			{
				close_self();
			}
		}
	}

    public override void enter()
    {
        base.enter();
		GetTree().Paused = false;
		Engine.TimeScale = 0.1;
		UpdateHandItem();
    }
	public override void exit()
	{
		base.exit();
		foreach (var name in (_player.CharacterData as PlayerData).Maps )
		{
			Label a = new Label();
			a.Text = name;
			_optionButton.Clear();
		}
		Engine.TimeScale = 1;
	}

	public void UpdateHandItem()
	{
		var children = _gridContainer.GetChildren();
		var datas = _equipItemGrid.GetChildren();
		for (int i = 0;i<children.Count;i++)
		{
			HandChooseSlot handChooseSlot = (HandChooseSlot)children[i];
			EquipItemSlot data = (EquipItemSlot)datas[i];
			handChooseSlot.item = data.item;
		}
		
		_optionButton.AddItem((_player.CharacterData as PlayerData).MapinHand);
		foreach (var name in (_player.CharacterData as PlayerData).Maps )
		{
			if(name != (_player.CharacterData as PlayerData).MapinHand)
			_optionButton.AddItem(name);
		}
	}

	public void OnOptionButtonItemSelected(long id)
	{
		var txt =_optionButton.GetItemText((int)id);
		(_player.CharacterData as PlayerData).MapinHand = txt;
	}
}
